#!/usr/bin/python2.6     
# -*- coding: utf-8 -*-     
import smtplib,sys,os,mimetypes
from email.mime.text import MIMEText     
from email.mime.image import MIMEImage     
from email.mime.multipart import MIMEMultipart    
LOG='/home/zhangzf/shell/logs/mbr.log'
DIR='/home/zhangzf/shell/logs'
DATE=os.popen('date +%y%m%d-%H:%M:%S').read().rstrip()
SM=sys.argv[1]
if os.path.exists(DIR)==False:
    os.makedirs(DIR)
def send_mail(sub,content,filename = None):     
    MF='/home/zhangzf/shell/mail_address_test.txt'
    mailto_list=[]
    mail_file=open('%s' %MF)
    for i in mail_file:
        i=i.strip()
        mailto_list.append(i)
    mail_host="mail.***.***"
    mail_user="*******
    mail_pass="******"
    message = MIMEMultipart()  
    message.attach(MIMEText(content)) 
    #message = MIMEText(content,_charset='gbk')     
    message['Subject'] = sub     
    message['From'] = mail_user     
    message['To'] = ";".join(mailto_list)     

    if filename != None and os.path.exists(filename):  
        ctype, encoding = mimetypes.guess_type(filename)  
        if ctype is None or encoding is not None:  
            ctype = "application/octet-stream" 
        maintype, subtype = ctype.split("/", 1)  
        attachment = MIMEImage((lambda f: (f.read(), f.close()))(open(filename, "rb"))[0], _subtype = subtype)  
        attachment.add_header("Content-Disposition", "attachment", filename = filename)  
        message.attach(attachment)

    try:     
        s = smtplib.SMTP()     
        s.connect(mail_host)     
        s.login(mail_user,mail_pass)     
        s.sendmail(mail_user, mailto_list, message.as_string())     
        s.close()     
        return True
    except Exception, e:     
        print str(e)     
        return False
if __name__ == '__main__':     
    if send_mail('%s-[67.32-%s]-The mongodb connection pool is null!Please login!'% (DATE,SM),'','/home/zhangzf/shell/mail.py'):     
	os.system('echo "%s--Master--Mail send successful"  >> %s' % (DATE,LOG))
    else:     
        os.system('echo "%s--Master--Mail send failed"  >> %s' % (DATE,LOG))
